

package com.hyphenate.chatuidemo.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chatuidemo.DemoApplication;
import com.hyphenate.chatuidemo.DemoHelper;
import com.hyphenate.chatuidemo.db.DemoDBManager;

import com.hyphenate.exceptions.HyphenateException;
import com.joplus.housekeeper.bean.User;
import com.joplus.housekeeper.core.Config;
import com.joplus.housekeeper.network.RequestHelper;
import com.joplus.housekeeper.network.TextCallback;
import com.joplus.housekeeper.utils.L;
import com.joplus.housekeeper.utils.NetWorkUtils;
import com.joplus.housekeeper.utils.SPUtils;
import com.joplus.housekeeper.utils.StringUtils;
import com.joplus.housekeeper.utils.T;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by bianxiang on 16/5/4.
 */
public class LoginIMUtil {
    static final String TAG = "LoginIMUtil";
    static Activity Aact;
    static String Ausername;
    static String Apassword;
    static Bundle Abundle;
    static User Auser;
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;


    public static void LoginIm(final Activity act, String accountId, final Bundle bundle) {
        DemoDBManager.getInstance().closeDB();
        Aact = act;
        RequestHelper.getInstance().getInfo(act, new TextCallback() {
            public void onFailure(String paramString) {
                L.e("拉取用户信息失败");

            }

            public void onSuccess(Object paramObject) {
                L.e("用户信息获取成功");
                try {
                    User localUser = (User) paramObject;
                    if (!localUser.getCode().equals("2000")) {
                        T.showShort(act, localUser.getMessage());

                        return;
                    }
                    DemoApplication.getInstance().setUser(localUser);
                    JPushInterface.setAlias(Aact, localUser.getData().getPushId(), mAliasCallback);
                    String str1 = (String) SPUtils.get(Aact, "PHONE", "");
                    L.d("LoginIm", localUser.toString());
                    if (!StringUtils.isEmpty(str1)) {
                        String str2 = "joPlus" + str1;
                        L.d("LoginIm", localUser.toString());
                        LoginIMUtil.login(Aact, str1, str2, bundle, localUser);
                        return;
                    }
                } catch (Exception localException) {

                }
            }
        });
    }

    private static void login(final Activity act, final String username, final String password, final Bundle bundle, final User user) {

        EMClient.getInstance().login(username, password, new EMCallBack() {
            public void onError(int paramInt, String paramString) {
                L.e(TAG, "login onError " + "paramInt:" + paramInt + " paramString:" + paramString);
                Aact = act;
                Ausername = username;
                Apassword = password;
                Abundle = bundle;
                Auser = user;
                try {
                    EMClient.getInstance().createAccount(username, password);
                    L.e("环信注册成功");
                    LoginIMUtil.login(Aact, username, password, bundle, user);
                    L.e("用户不存在");
                    return;
                } catch (HyphenateException localHyphenateException) {

//
                    localHyphenateException.printStackTrace();
                }

            }

            public void onProgress(int paramInt, String paramString) {
            }

            public void onSuccess() {
                L.e("环信登录成功");
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                if (!EMClient.getInstance().updateCurrentUserNick(DemoApplication.currentUserNick.trim()))
                    Log.e("LoginActivity", "update current user nick fail");
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
                String accoundId = DemoApplication.getInstance().getAccountId();
                turnloginOrSetNme(Aact, accoundId, bundle, user);

            }
        });
    }


    /**
     * 跳转到填写聊天界面还是填写用户信息
     *
     * @param act
     * @param accountId
     * @param bundle
     * @param user
     */
    private static void turnloginOrSetNme(final Activity act, final String accountId, final Bundle bundle, final User user) {




    }

    private static final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    L.i(TAG, logs);
                    if (NetWorkUtils.isNetworkAvailable(Aact)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }


        }

    };


    private static final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    L.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(Aact, (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    L.d(TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(Aact, null, (Set<String>) msg.obj, mAliasCallback);
                    break;

                default:
                    L.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };


}
